package com.fuyun.microservice.handler;

import com.alibaba.fastjson.JSON;
import com.fuyun.microservice.codec.PacketType;
import com.fuyun.microservice.codec.msg.Header;
import com.fuyun.microservice.codec.msg.QueryRequestMessage;
import com.fuyun.microservice.codec.msg.QueryResponseMessage;
import com.fuyun.microservice.proxy.ForwardFactory;
import com.fuyun.microservice.proxy.ForwardResult;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class ProxyMessageHandler extends AuthAbstractHandler<QueryRequestMessage> {
    private final ForwardFactory forwardFactory;

    public ProxyMessageHandler(ForwardFactory forwardFactory) {
        this.forwardFactory = forwardFactory;
    }

    /**
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, QueryRequestMessage msg) throws Exception {
        channelAuth(ctx,msg);

        Header header = msg.getHeader();
        if (header.getCommandId() != PacketType.QUERYRESPONSE.getCommandId()) {
            ctx.fireChannelRead(msg);
        }

        log.debug("client body:{}", msg.toString());
        QueryResponseMessage responseMessage = new QueryResponseMessage(msg.getHeader().getSequenceNo());
        ForwardResult forwardResult = forwardFactory.forward(msg);
        responseMessage.setResultCode(forwardResult.getCode());
        responseMessage.setResultMessage(forwardResult.getMsg());
        responseMessage.setResultBody(JSON.toJSONString(forwardResult.getData()));

        ctx.channel().writeAndFlush(responseMessage);
        ctx.fireChannelReadComplete();
    }

}
